package icom.acm.action;
/**
 * @author shench
 */
import icom.acm.bean.T_USER;
import icom.acm.bean.T_USERONLINE;
import icom.acm.bean.T_USERVO;
import icom.acm.manager.T_UserMgr;
import icom.acm.manager.T_UserOnlineMgr;
import icom.acm.net.EmailThread;
import icom.acm.util.DBConnect;
import icom.acm.util.json.JSONMsg;

import java.io.IOException;
import java.io.PrintWriter;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;


public class UserAction extends Action{	
	/**
	 * 以下变量需要有get set方法，这样html中传入的参数就可以自动得到
	 * 如果是基本类型int，String。。。的变量 html中形式：http://..../xx?a=?
	 * 如果是自定义变了则: http://..../xx?u.id=?&u.xx=?
	 */
	private T_USER u;	
	private T_USERVO uvo;
	private String token;	
	
	public void sendPassword(){
System.out.println("sendPassword");		
		// 防止重复提交
		String token = (String)session.getAttribute("token_forget");
		if (token==null){
			return ;
		} else if (!token.equals(this.token)){
			return ;
		}
		session.removeAttribute("token_forget");
		
		String s = icom.acm.util.RandUtil.rndString(7);
		u.setU_PASSWORD(s);
		T_UserMgr um = new T_UserMgr();
		int res = um.updatePasswordByEmail(u);	// 更新密码
		System.out.println("res=" +res);
		if (res==1)	{			
			EmailThread et = new EmailThread("您使用Coding更新了密码",u.getU_EMAIL(),"随机密码",
					"Coding已经重设您的密码是<font size='5' color='red'>"+s+"</font><br/>" +
							"请记住你的密码，登录后建议修改！");
			et.start();
		}
	}
	
	public String forget(){
		toUrl = "forget.jsp";
		
		return "TOURL";
	}
	
	public void checkAccount(){
System.out.println("checkaccount");	
		
		try {
			u = new T_USER();
			String res = "";
			if (type.intValue()==0){				
				u.setU_EMAIL(uvo.getId());
				T_UserMgr um = new T_UserMgr();
				T_USER user = um.selectByEmail(u);				
				if (user!=null)					
					res = user.getU_NICKNAME();
			} else if (type.intValue()==1){
				u.setU_NICKNAME(uvo.getId());
				T_UserMgr um = new T_UserMgr();
				T_USER user = um.selectByNickName(u);				
				if (user!=null)					
					res = user.getU_NICKNAME();				
			}
			PrintWriter out = response.getWriter();
			out.append(res);
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	public String register() throws Exception {
		// 防止重复提交
		String token = (String)session.getAttribute("token");
		if (token==null){
			return "ERROR";
		} else if (!token.equals(this.token)){
			return "ERROR";
		}
		session.removeAttribute("token");
		
/*		response.setContentType("text/html; charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Pragma","No-cache"); 
		response.setHeader("Cache-Control","no-cache"); 
		response.setDateHeader("Expires", 0); */
		
		System.out.println("user register!");		
		System.out.println(uvo.getU_EMAIL()+"\n"+uvo.getU_NICKNAME()+"\n"+uvo.getU_PASSWORD());
		if (uvo.getU_EMAIL()==null || uvo.getU_EMAIL().equals("")){			
			return "ERROR";
		} else if (uvo.getU_PASSWORD()==null || uvo.getReU_PASSWORD().equals("")) {
			return "ERROR";
		} else if (uvo.getReU_PASSWORD()==null || uvo.getReU_PASSWORD().equals("")) {
			return "ERROR";
		} else if (!uvo.getReU_PASSWORD().equals(uvo.getU_PASSWORD())){
			return "ERROR";
		} else if (uvo.getU_NICKNAME()== null || uvo.getU_NICKNAME().equals("")){
			return "ERROR";
		}		
		String ver = (String)session.getAttribute("verification");
		System.out.println(ver + "\t" + uvo.getVerification());
		if (!ver.equals(uvo.getVerification())){			
			out.println("验证码错误");
			return "ERROR";
		}
		u = uvo.vo2bean();
		T_UserMgr um = new T_UserMgr();
		int id = um.insert(u);
		if (id==-1){
			return "ERROR";
		}
		u.setU_ID(id);
		session.setAttribute("user", u);
		
		
		return "SUCCESS";
	}

	public void login(){
		JSONMsg jmsg = null;
		u = new T_USER();
		u.setU_NICKNAME(uvo.getId());
		u.setU_EMAIL(uvo.getId());
		u.setU_PASSWORD(uvo.getU_PASSWORD());
		T_UserMgr um = new T_UserMgr();
		T_UserOnlineMgr uomgr = new T_UserOnlineMgr();
		DBConnect db = new DBConnect();
		
		try {
			T_USER user = um.selectByEMAILOrNICKNAMEAndPASSWORD(u, db);
			if (user==null){
				jmsg = new JSONMsg(false, "用户不存在!");
				out.print(jmsg.toString());				
			} else if (user.getU_ROLE()<0){
				jmsg = new JSONMsg(false, "用户未激活!");
				out.print(jmsg.toString());				
			} else {
				session.setAttribute("user", user);
				T_USERONLINE uo = new T_USERONLINE();
				uo.setUO_U_ID(user.getU_ID());
				uo.setUO_SESSIONID(session.getId());
				uomgr.insert(uo, db);
				jmsg = new JSONMsg(true, "成功登录!");
				out.print(jmsg.toString());
			}
		} catch(MySQLIntegrityConstraintViolationException ex){
			jmsg = new JSONMsg(false, "未知的错误!");
			out.print(jmsg.toString());
			ex.printStackTrace();
		} catch(Exception ex){
			jmsg = new JSONMsg(false, "未知的错误!");
			out.print(jmsg.toString());
			ex.printStackTrace();
		} finally {
			db.close();
		}
	}
	/**
	 * 用户退出
	 */
	public void quit(){
		JSONMsg jmsg = null;
		T_USER u = this.checkUser();
		if (u==null){
			jmsg = new JSONMsg(false, "用户未登录!");
			out.print(jmsg.toString());
			return ;
		}
		
		session.removeAttribute("user");
		jmsg = new JSONMsg(true, "成功推出!");
		out.print(jmsg.toString());
	}
	
	public String index(){	
		T_USER user = (T_USER)session.getAttribute("user");
		if (user==null){
			toUrl = "index.jsp";
			return "TOURL";
		}
		request.setAttribute("req_user", user.toJson());
		return "INDEX";
	}
	
	public T_USERVO getUvo() {
		return uvo;
	}

	public void setUvo(T_USERVO uvo) {
		this.uvo = uvo;
	}

	public String getToken() {
		return token;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public T_USER getU() {
		return u;
	}

	public void setU(T_USER u) {
		this.u = u;
	}	
}
